/**
 * @create 2022-06-2
 * @desc auto-i18n
 */

const {declare} = require('@babel/helper-plugin-utils');
const generate = require('@babel/generator').default;

// 1. 模块中没有引入 intl 模块，需要先自动引入
// 2. 将字符串、模板字符串中的字符替换为 inil.t 函数调用的形式
// 3. 将收集到的值收集起来，输入到一个静态文件中
// 4. 支持通过 /* i18n-disable */ 忽略
module.exports = declare((api, options, dirname) => {
    api.assertVersion(7);

    const save = (file, key, value) => {
        const allText = file.get('allText');
        allText[key] = value;
        file.set('allText', allText);
    }

    const getReplaceExpression = (path, key, i18nImportID) => {

        // 获取 所有变量 的表达式
        const expressionParams = path.isTemplateLiteral()
            ? path.node.expressions.map(item => generate(item).code)
            : null
        const rightStr = expressionParams ? `, ${expressionParams.join(',')})` : ')';
        let replaceExpression = api.template.ast(`${i18nImportID}.t(${key}${rightStr}`).expression;

        // <div title="这种情况" tip={"非这种情况"}></div>
        if (path.findParent(p => p.isJSXAttribute()) && !path.findParent(p=> p.isJSXExpressionContainer())) {
            replaceExpression = api.types.JSXExpressionContainer(replaceExpression);
        }

        return replaceExpression;
    }

    return {
        pre(file) {
            file.set('allText', {});
        },
        post(file) {
            const allText = file.get('allText');
            console.log(allText);
        },
        visitor: {
            Program(path, state) {
                let imported;
                path.traverse({
                    ImportDeclaration(importPath) {
                        const source = importPath.node.source.value;
                        if (source === 'intl') {
                            imported = true;
                        }
                    }
                })

                if (!imported) {
                    const uid = path.scope.generateUid('intl');
                    path.node.body.push(api.template.ast(`import ${uid} from 'intl'`));
                    state.i18nImportID = uid;
                }

                path.traverse({
                    'StringLiteral|TemplateLiteral'(path, state) {
                        if (path.node.leadingComments) {
                            // 去掉 i18n-disable 的节点
                            path.node.leadingComments = path.node.leadingComments.filter((comment, index) => {
                                if (comment.value.includes('i18n-disable')) {
                                    path.node.skipTransform = true;
                                    return false;
                                }
                                return true;
                            })
                        }

                        // import 语句中的 StringLiteral
                        if (path.findParent(p => p.isImportDeclaration())) {
                            path.node.skipTransform = true;
                        }
                    }
                })
            },
            'StringLiteral' (path, state) {
                if (path.node.skipTransform) {return}

                const key = nextIntlKey();
                const value = path.node.value;

                save(state.file, key, value);

                const replaceExpression = getReplaceExpression(path, key, state.i18nImportID);
                path.replaceWith(replaceExpression);
                path.skip();
            },
            'TemplateLiteral' (path, state) {
                if (path.node.skipTransform) {return}

                const key = nextIntlKey();
                const value = path.get('quasis').map(item => item.node.value.raw).join('{placeholder}');

                if (!value) { return; }
                save(state.file, key, value);

                const replaceExpression = getReplaceExpression(path, key, state.intlUid);
                path.replaceWith(replaceExpression);
                path.skip();

            }
        }
    }
})

let intlIndex = 0;
function nextIntlKey() {
    ++intlIndex;
    return `intl${intlIndex}`;
}
